package com.fujin.gulimall.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.fujin.common.Vo.SkuEsModel;
import com.fujin.gulimall.search.config.ElasticSearchConfig;
import com.fujin.gulimall.search.constant.EsConstant;
import com.fujin.gulimall.search.service.productSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @title: productSaveServiceImpl
 * @Author Tan
 * @Date: 2022/2/1 16:57
 * @Version 1.0
 */
@Slf4j
@Service
public class productSaveServiceImpl implements productSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            //将保存的信息转为json格式 进行保存
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        //对错误es返回的错误信息进行处理
        //bulk.hasFailures()判断有误错误
        boolean b = bulk.hasFailures();

        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.error("商品上架成功:{}",collect);
        return b;
    }
}
